package edu.sysu.demo.rabbitmq.config;

import edu.sysu.demo.rabbitmq.Publisher;
import edu.sysu.demo.rabbitmq.RandomStringBuilder;
import edu.sysu.demo.rabbitmq.data.entity.Deal;
import edu.sysu.demo.rabbitmq.data.entity.Item;
import edu.sysu.demo.rabbitmq.data.entity.User;
import java.math.BigDecimal;
import java.util.Random;
import org.apache.commons.math3.random.RandomAdaptor;
import org.apache.commons.math3.random.Well19937c;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

@Configuration
public class ScheduleConfig {

  private Publisher publisher;

  private final RandomStringBuilder builder = RandomStringBuilder.newBuilder()
      .useDigit()
      .useLowerCase()
      .useSymbol()
      .useUpperCase();

  private Random random = new RandomAdaptor(new Well19937c());

  private Item item = Item.builder()
      .id(random.nextLong())
      .name(builder.build(13))
      .unitPrice(BigDecimal.valueOf(15.00))
      .build();

  @Scheduled(fixedRate = 1000L)
  public void sendMessage() {

    String buyerName = builder.build(10);
    User buyer = User.builder()
        .username(buyerName)
        .build();

    String sellerName = builder.build(15);
    User seller = User.builder()
        .username(sellerName)
        .build();

    Deal deal = Deal.builder()
        .buyer(buyer)
        .seller(seller)
        .item(item)
        .build();

    publisher.enqueue(deal);
  }

  @Autowired
  public void setPublisher(Publisher publisher) {
    this.publisher = publisher;
  }
}
